//app.js
var apiHelp = require('utils/api.js');
App({
  onLaunch: function () {
    //调用API从本地缓存中获取数据
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    var that = this;
    that.getUserInfo(function(userInfo){

      that.getUserOpendId(function (opendId) {
        var params = { "opendId": opendId, "nickName": userInfo.nickName, "avatarUrl": userInfo.avatarUrl, "gender": userInfo.gender, "province": userInfo.province, "city": userInfo.city, "country": userInfo.country};

        var url = apiHelp.addOrUpdateUser();
        apiHelp.request(url, 'POST', params, function (data, err) {
          that.globalData.roleCode = data.tips;
        });
        
      });

    });
    
  },
  getUserInfo:function(cb){

    var that = this
    if(this.globalData.userInfo){
      typeof cb == "function" && cb(this.globalData.userInfo)
    }else{
      //调用登录接口
      wx.login({
        success: function () {
          wx.getUserInfo({
            success: function (res) {
              that.globalData.userInfo = res.userInfo
              typeof cb == "function" && cb(that.globalData.userInfo)
            }
          })
        }
      })
    }
  },
  getUserOpendId: function (cb){
    var that = this;
    wx.login({
      success: function (loginCode) {
        var url = apiHelp.getOpendId();
        apiHelp.request(url, 'GET', { "jsCode": loginCode.code}, function (data, err) {
          that.globalData.opendId = data.openid;
          typeof cb == "function" && cb(data.openid);
        });

        /*
        var appid = 'wxeb9de6dbcfde9826'; //填写微信小程序appid  
        var secret = '16e4ba388eabe0d4eda90ca17748a4ca'; //填写微信小程序secret  
        var url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + appid + '&secret=' + secret + '&grant_type=authorization_code&js_code=' + loginCode.code;
        debugger;
        //调用request请求api转换登录凭证  
        wx.request({
          url: url,
          header: {
            'content-type': 'application/json'
          },
          success: function (res) {
            debugger;
            that.globalData.opendId = res.data.openid;
            typeof cb == "function" && cb(res.data.openid);
            
          }
        })*/
      }
    })  

  },
  globalData:{
    userInfo:null,
    opendId:"",
    roleCode:""
  }
})